<template>
  <el-drawer
    v-model="drawerVisible"
    :with-header="false"
    size="50%"
    direction="rtl"
    :close-on-click-modal="true"
    :show-close="true"
    custom-class="download-drawer"
  >
    <div class="drawer-header">
      <span class="drawer-title-bar"></span>
      <span class="drawer-title">下载管理</span>
      <el-icon class="drawer-close" @click="handleClose"><Close /></el-icon>
    </div>
    <div class="download-progress">
      <!-- 当前下载任务 -->
      <div v-if="currentDownloads.length > 0" class="current-downloads">
        <h3>当前下载</h3>
        <div class="download-list">
          <div
            v-for="download in currentDownloads"
            :key="download.id"
            class="download-item"
          >
            <div class="download-info">
              <el-icon class="download-icon">
                <component :is="getFileIcon(download.filename)" />
              </el-icon>
              <div class="file-info">
                <div class="filename">{{ download.filename }}</div>
                <div class="progress-info">
                  <el-progress
                    :percentage="download.progress"
                    :status="download.status === 'error' ? 'exception' : undefined"
                    :stroke-width="6"
                  />
                  <span class="progress-text">
                    {{ download.progress }}% - {{ download.speed }}
                  </span>
                </div>
              </div>
            </div>
            <div class="download-actions">
              <el-button
                v-if="download.status === 'completed'"
                size="small"
                @click="openFileLocation(download.filePath)"
              >
                在文件夹中显示
              </el-button>
              <el-button
                v-if="download.status === 'downloading'"
                size="small"
                @click="cancelDownload(download.id)"
              >
                取消
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史下载任务 -->
      <div class="history-downloads">
        <h3>下载历史</h3>
        <div class="download-list">
          <div
            v-for="download in historyDownloads"
            :key="download.id"
            class="download-item history-item"
          >
            <div class="download-info">
              <el-icon class="download-icon">
                <component :is="getFileIcon(download.filename)" />
              </el-icon>
              <div class="file-info">
                <div 
                  class="filename"
                  :class="{ 'file-deleted': !download.exists }"
                >
                  {{ download.filename }}
                </div>
                <div 
                  class="file-path"
                  :class="{ 'file-deleted': !download.exists }"
                >
                  {{ download.filePath }}
                </div>
                <div class="download-time">
                  {{ formatTime(download.completedAt) }}
                </div>
              </div>
            </div>
            <div class="download-actions">
              <el-tooltip :content="download.exists ? '在文件夹中显示' : '已删除'" placement="top">
                <el-button
                  size="small"
                  :disabled="!download.exists"
                  @click="openFileLocation(download.filePath)"
                  class="icon-btn"
                >
                  <el-icon><FolderOpened /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除记录" placement="top">
                <el-button
                  size="small"
                  @click="removeFromHistory(download.id)"
                  class="icon-btn"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="currentDownloads.length === 0 && historyDownloads.length === 0" class="empty-state">
        <el-empty description="暂无下载记录" />
      </div>
    </div>

    <div class="drawer-footer-bar">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        v-if="historyDownloads.length > 0"
        type="danger"
        @click="clearHistory"
      >
        清空历史
      </el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { 
  Download, 
  FolderOpened, 
  Folder, 
  Close, 
  Delete,
  Document,
  Picture,
  VideoPlay,
  Microphone,
  Files,
  DocumentCopy,
  Grid,
  Collection
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible'])

// 当前下载任务
const currentDownloads = ref([])
// 历史下载任务
const historyDownloads = ref([])

// 对话框可见性
const drawerVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听抽屉打开，重新检查文件存在性
watch(drawerVisible, async (newVal) => {
  if (newVal && historyDownloads.value.length > 0) {
    await Promise.all(historyDownloads.value.map(async (download) => {
      download.exists = await checkFileExists(download.filePath)
    }))
  }
})

// 格式化时间
function formatTime(timestamp) {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 检查文件是否存在
async function checkFileExists(filePath) {
  try {
    if (window.electronAPI?.checkFileExists) {
      const exists = await window.electronAPI.checkFileExists(filePath)
      console.log('检查文件存在:', filePath, '结果:', exists)
      return exists
    }
    console.warn('electronAPI.checkFileExists 不存在，返回 false')
    return false // 当API不存在时，保守地返回false
  } catch (error) {
    console.error('检查文件存在失败:', error)
    return false
  }
}

// 打开文件位置
async function openFileLocation(filePath) {
  const currentExists = await checkFileExists(filePath)
  if (!currentExists) {
    ElMessage.warning('文件已删除，无法打开位置');
    
    // 更新历史记录中对应文件的exists状态
    const historyItem = historyDownloads.value.find(d => d.filePath === filePath)
    if (historyItem) {
      historyItem.exists = false
      // 保存更新后的历史记录
      saveHistoryToStorage()
    }
    
    return;
  }
  
  try {
    if (window.electronAPI?.openFileLocation) {
      window.electronAPI.openFileLocation(filePath)
    } else {
      if (window.webviewAPI?.openFileLocation) {
        window.webviewAPI.openFileLocation(filePath)
      }
    }
  } catch (error) {
    console.error('打开文件位置失败:', error)
    ElMessage.error('打开文件位置失败')
  }
}

// 监听下载进度更新
function setupDownloadProgressListener() {
  if (window.electronAPI?.onDownloadProgress) {
    window.electronAPI.onDownloadProgress((data) => {
      const { action, downloadId, data: progressData } = data
      switch (action) {
        case 'add':
          addDownload(progressData)
          break
        case 'progress':
          updateDownloadProgress(downloadId, progressData.progress, progressData.speed)
          break
        case 'complete':
          completeDownload(downloadId, progressData.filePath)
          break
        case 'error':
          failDownload(downloadId, progressData.error)
          break
      }
    })
  }
}

// 移除下载进度监听
function removeDownloadProgressListener() {
  if (window.electronAPI?.removeDownloadProgressListener) {
    window.electronAPI.removeDownloadProgressListener()
  }
}

// 取消下载
function cancelDownload(downloadId) {
  const download = currentDownloads.value.find(d => d.id === downloadId)
  if (download) {
    download.status = 'cancelled'
    download.progress = 0
    // 通知主进程取消下载
    if (window.electronAPI?.cancelDownload) {
      window.electronAPI.cancelDownload(downloadId)
    }
    // 从当前下载列表中移除
    currentDownloads.value = currentDownloads.value.filter(d => d.id !== downloadId)
    ElMessage.info('下载已取消')
  }
}

// 从历史记录中删除
function removeFromHistory(downloadId) {
  historyDownloads.value = historyDownloads.value.filter(d => d.id !== downloadId)
  saveHistoryToStorage()
  ElMessage.success('记录已删除')
}

// 清空历史记录
function clearHistory() {
  historyDownloads.value = []
  saveHistoryToStorage()
  ElMessage.success('历史记录已清空')
}

// 保存历史记录到本地文件
async function saveHistoryToStorage() {
  try {
    // 转换为纯数据，避免Vue响应式对象序列化错误
    const pureHistory = historyDownloads.value.map(download => ({
      id: download.id,
      filename: download.filename,
      filePath: download.filePath,
      progress: download.progress,
      speed: download.speed,
      status: download.status,
      startedAt: download.startedAt,
      completedAt: download.completedAt,
      exists: download.exists
    }))
    await window.electronAPI.writeDownloadHistory(pureHistory)
  } catch (error) {
    console.error('保存下载历史失败:', error)
  }
}

// 从本地文件加载历史记录
async function loadHistoryFromStorage() {
  try {
    const history = await window.electronAPI.readDownloadHistory()
    if (history) {
      historyDownloads.value = history
      // 检查文件是否存在
      await Promise.all(historyDownloads.value.map(async (download) => {
        download.exists = await checkFileExists(download.filePath)
      }))
    }
  } catch (error) {
    console.error('加载下载历史失败:', error)
  }
}

// 添加下载任务
function addDownload(downloadInfo) {
  const download = {
    id: downloadInfo.downloadId,
    filename: downloadInfo.filename,
    filePath: downloadInfo.filePath,
    progress: 0,
    speed: '0 KB/s',
    status: 'downloading',
    startedAt: new Date().toISOString()
  }
  currentDownloads.value.push(download)
  return download.id
}

// 更新下载进度
function updateDownloadProgress(downloadId, progress, speed) {
  const download = currentDownloads.value.find(d => d.id === downloadId)
  if (download) {
    download.progress = progress
    download.speed = speed
  }
}

// 完成下载
async function completeDownload(downloadId, filePath) {
  const download = currentDownloads.value.find(d => d.id === downloadId)
  if (download) {
    download.status = 'completed'
    download.progress = 100
    download.filePath = filePath
    download.completedAt = new Date().toISOString()
    // 检查文件是否实际存在
    const fileExists = await checkFileExists(filePath)
    // 移动到历史记录 - 只保存纯数据，避免Vue响应式对象序列化错误
    const historyItem = {
      id: download.id,
      filename: download.filename,
      filePath: download.filePath,
      progress: download.progress,
      speed: download.speed,
      status: download.status,
      startedAt: download.startedAt,
      completedAt: download.completedAt,
      exists: fileExists
    }
    historyDownloads.value.unshift(historyItem)
    // 从当前下载列表中移除
    currentDownloads.value = currentDownloads.value.filter(d => d.id !== downloadId)
    // 保存历史记录
    saveHistoryToStorage()
  }
}

// 下载失败
function failDownload(downloadId, error) {
  const download = currentDownloads.value.find(d => d.id === downloadId)
  if (download) {
    download.status = 'error'
    download.error = error
    // 从当前下载列表中移除
    currentDownloads.value = currentDownloads.value.filter(d => d.id !== downloadId)
    ElMessage.error(`下载失败: ${error}`)
  }
}

// 关闭对话框
function handleClose() {
  emit('update:visible', false)
}

// 暴露方法给父组件
defineExpose({
  addDownload,
  updateDownloadProgress,
  completeDownload,
  failDownload
})

// 根据文件后缀名获取图标
function getFileIcon(filename) {
  if (!filename) return Folder
  const extension = filename.toLowerCase().split('.').pop()
  // 图片文件
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico', 'tiff'].includes(extension)) {
    return Picture
  }
  // 视频文件
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v', '3gp'].includes(extension)) {
    return VideoPlay
  }
  // 音频文件
  if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a'].includes(extension)) {
    return Microphone
  }
  // 表格文件
  if (['xls', 'xlsx', 'csv', 'ods'].includes(extension)) {
    return Grid
  }
  // 演示文件
  if (['ppt', 'pptx', 'odp'].includes(extension)) {
    return Collection
  }
  // 压缩文件
  if (['zip', 'rar', '7z', 'tar', 'gz', 'bz2'].includes(extension)) {
    return Files
  }
  // 代码文件
  if (['js', 'ts', 'html', 'css', 'json', 'xml', 'py', 'java', 'cpp', 'c', 'php', 'rb', 'go', 'rs', 'swift', 'kt'].includes(extension)) {
    return DocumentCopy
  }
  // 文档文件和其他文件
  if (['pdf', 'doc', 'docx', 'txt', 'rtf', 'odt'].includes(extension)) {
    return Document
  }
  // 匹配不到任何文件类型时返回Folder图标
  return Folder
}

onMounted(() => {
  loadHistoryFromStorage()
  setupDownloadProgressListener()
})

onBeforeUnmount(() => {
  saveHistoryToStorage()
  removeDownloadProgressListener()
})
</script>

<style scoped lang="scss">
.download-drawer {
  .el-drawer__header {
    display: none;
  }
  .el-drawer__body {
    padding: 18px 18px 0 18px;
    background: #fafcff;
    height: 100vh;
    padding-bottom: 70px;
  }
}
.drawer-header {
  display: flex;
  align-items: center;
  height: 48px;
  padding: 0 0 12px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  .drawer-title-bar {
    width: 4px;
    height: 22px;
    background: #409eff;
    border-radius: 2px;
    margin-right: 12px;
    flex-shrink: 0;
  }
  .drawer-title {
    font-size: 18px;
    font-weight: 600;
    color: #222;
    flex: 1;
  }
  .drawer-close {
    font-size: 20px;
    color: #909399;
    cursor: pointer;
    margin-left: 8px;
    transition: color 0.2s;
    &:hover {
      color: #409eff;
    }
  }
}
.download-progress {
  padding-bottom: 50px;
  .current-downloads,
  .history-downloads {
    margin-bottom: 18px;
    h3 {
      margin: 0 0 10px 0;
      font-size: 15px;
      font-weight: 600;
      color: #303133;
    }
  }
  .download-list {
    .download-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 7px;
      background: #fff;
      transition: all 0.3s;
      &:hover {
        background: #f5f7fa;
        border-color: #c0c4cc;
      }
      &.history-item {
        background: #fafcff;
        &:hover {
          background: #f5f7fa;
        }
      }
      .download-info {
        display: flex;
        align-items: center;
        flex: 1;
        min-width: 0;
        .download-icon {
          font-size: 20px;
          color: #409eff;
          margin-right: 12px;
          flex-shrink: 0;
        }
        .file-info {
          flex: 1;
          min-width: 0;
          .filename {
            font-weight: 500;
            color: #303133;
            margin-bottom: 4px;
            word-break: break-all;
            &.file-deleted {
              color: #c0c4cc;
              text-decoration: line-through;
            }
          }
          .file-path {
            font-size: 12px;
            color: #909399;
            margin-bottom: 2px;
            word-break: break-all;
            &.file-deleted {
              color: #c0c4cc;
              text-decoration: line-through;
            }
          }
          .download-time {
            font-size: 12px;
            color: #c0c4cc;
          }
          .progress-info {
            display: flex;
            align-items: center;
            gap: 8px;
            .progress-text {
              font-size: 12px;
              color: #606266;
              white-space: nowrap;
            }
          }
        }
      }
      .download-actions {
        display: flex;
        gap: 4px;
        flex-shrink: 0;
        margin-left: 16px;
      }
    }
  }
  .empty-state {
    text-align: center;
    padding: 40px 0;
  }
}
.drawer-footer-bar {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px 18px;
  background: #fafcff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  z-index: 10;
}
.file-deleted {
  color: #aaa;
  text-decoration: line-through;
}
.icon-btn {
  border-radius: 50%;
  width: 32px;
  height: 32px;
  padding: 0;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  color: #606266;
  transition: all 0.3s;
  
  &:hover {
    background: #e4e7ed;
    border-color: #c0c4cc;
    color: #303133;
  }
  
  &:disabled {
    background: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor: not-allowed;
  }
  
  .el-icon {
    font-size: 14px;
  }
}
</style> 